<?php


namespace Beerus\Modules\BrandActivity\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\cache\lottery\CActivityContent;
use Biz\model\springHomeDecActivity\ActivityContent;
use Biz\model\springHomeDecActivity\ContentTopic as mContentTopic;
use Biz\service\springHomeDecActivity\Util;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Biz\pockets\constInterface\SpringHomeDecConfig;

class ContentController extends Controller
{
    const  PAGE_SIZE = 20;

    public function index(Request $request, Content $content): Content
    {
        $request_data = $request->all();
        $condition = self::getCondition($request_data);
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $where = $condition;
        $where['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        $where['topic_id[!]'] = 0;
        $list = ActivityContent::dataSelect($where);
        unset($where['LIMIT']);
        $total = ActivityContent::dataCount($where);
        $gridModel = new GridDataModel($list, $total, [
            'perPage' => $page_size,
        ]);

        $topics = [];
        $date = $condition['show_date'] ?? null;
        if(!$date){
            $date = date('Y-m-d', time());
        }
        $activityBeginTime = strtotime(SpringHomeDecConfig::ACTIVITY_TIME_START);
        if (time() < $activityBeginTime) {
            $date = date('Y-m-d', $activityBeginTime);
        }
        $activityEndTime = strtotime(SpringHomeDecConfig::ACTIVITY_TIME_END);
        if (time() >= $activityEndTime) {
            $date = date('Y-m-d', $activityEndTime);
        }
        $mainTopic = mContentTopic::getMainTopic($date);
        if ($mainTopic) {
            $mwhere['is_main'] = mContentTopic::IS_MAIN_NO;
            $mwhere['is_test'] = Util::isTest();
            //$mwhere['main_topic_id'] = $mainTopic['topic_id'];
            $mwhere['data_status'] = mContentTopic::STATUS_NORMAL;
            //$mwhere['show_date'] = $date;
            $mwhere['ORDER'] = ['weight' => 'ASC'];
            $result = mContentTopic::dataSelect($mwhere);
            if ($result && is_array($result)) {
                //$topics = array_column($result, 'name', 'id');
                foreach ($result as $tp){
                    $topics[$tp['id']] = $tp['name'] . "[{$tp['id']}]";
                }
            }
        }

        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $topics) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableActions();
                $grid->filter(function ($filter) use ($topics) {
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) use ($topics) {
                        $filter->equal('topic_id', '主题ID')->select($topics);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('show_date', '展示日期')->date('Y-m-d');
                        $filter->equal('obj_id', '对象ID')->placeholder('对象ID');
                    });

                    $filter->expand();//默认展开
                });
                $grid->column('id', '主键ID');
                $grid->column('topic_id', '主题')->display(function ($topic_id) use ($topics) {
                    $v = $topics[$topic_id] ?? $topic_id;
                    return $v;
                });
                $grid->column('obj_id', '对象id')->editable();
                $grid->column('obj_type', '类型')->display(function ($obj_type) {
                    $values = ['note', '整屋'];
                    return $values[$obj_type] ?? '';
                });
                $grid->column('show_date', '展示日期')->editable();
                $grid->column('data_status', '数据状态')->editable();
                $grid->column('is_show', '是否展示')->editable();
                $grid->column('is_test', '是否测试')->editable();
                $grid->column('weight', '权重')->editable();
                $grid->column('create_time', '添加时间');
            });

        $tab = new Tab();
        $tab->add('活动内容列表', $grid->render(), true);
        $content->row($tab);

        return $content
            ->header('活动内容列表')
            ->description(' ')
            ->breadcrumb(['text' => '活动内容列表', 'url' => '/brandActivity/scontent']);
    }


    private static function getCondition($request): array
    {
        $condition = [];
        if (isset($request['id']) && !empty($request['id'])) {
            $condition['id'] = $request['id'];
        }
        if (isset($request['topic_id']) && !empty($request['topic_id'])) {
            $condition['topic_id'] = $request['topic_id'];
        }
        if (isset($request['show_date']) && !empty($request['show_date'])) {
            $condition['show_date'] = $request['show_date'];
        }
        if (isset($request['obj_id']) && !empty($request['obj_id'])) {
            $condition['obj_id'] = $request['obj_id'];
        }
        return $condition;
    }

    public function create(Content $content, Form $form): Content
    {
        $date = date('Y-m-d', time());

        $activityBeginTime = strtotime(SpringHomeDecConfig::ACTIVITY_TIME_START);
        if (time() < $activityBeginTime) {
            $date = date('Y-m-d', $activityBeginTime);
        }
        $activityEndTime = strtotime(SpringHomeDecConfig::ACTIVITY_TIME_END);
        if (time() >= $activityEndTime) {
            $date = date('Y-m-d', $activityEndTime);
        }
        $topics = [];
        $mainTopic = mContentTopic::getMainTopic($date);
        if ($mainTopic) {
            $mwhere['is_main'] = mContentTopic::IS_MAIN_NO;
            $mwhere['is_test'] = Util::isTest();
            $mwhere['data_status'] = mContentTopic::STATUS_NORMAL;
            $mwhere['show_date[>=]'] = date('Y-m-d', time());
            $mwhere['ORDER'] = ['weight' => 'ASC'];
            $result = mContentTopic::dataSelect($mwhere);
            if ($result && is_array($result)) {
            //array_column($result, 'name', 'id');
                foreach ($result as $tp){
                    $topics[$tp['id']] = $tp['name'] . "[{$tp['id']}]";
                }
            }
        }
        $form->disableReset();
        $options = [0 => 'note', 1 => '整屋'];
        $form->select('obj_type', '类型')->options($options)->default(0);
        $form->text('obj_id', "obj id")->required();
        $form->date('show_date', "展示日期")->required()->default(date('Y-m-d',time()));
        $form->select('topic_id', "主题")->options($topics)->required();
        $options1 = ['否', '是'];
        $form->select('is_show', '是否展示')->options($options1)->default(1);
        $form->select('is_test', '是否测试')->options($options1)->default(0);
        $form->text('weight', "排序")->default(0);
        $form->confirm('确定创建吗？');

        $form->action('/admin/brandActivity/scontent/save');
        return $content
            ->header('新增')
            ->description(' ')
            ->breadcrumb(
                ['text' => '活动内容列表', 'url' => '/brandActivity/scontent'],
                ['text' => '新增']
            )
            ->row($form);
    }

    public function save(Request $request)
    {
        $params = $request->all();
        $data = [
            'show_date' => $params['show_date'],
            'topic_id' => $params['topic_id'],
            'obj_id' => $params['obj_id'],
            'obj_type' => $params['obj_type'],
            'data_status' => ActivityContent::STATUS_NORMAL,
            'is_show' => $params['is_show'],
            'is_test' => $params['is_test'],
            'weight' => $params['weight'],
            'create_time' => date('Y-m-d H:i:s', time()),
            'update_time' => date('Y-m-d H:i:s', time()),
        ];
        $result = ActivityContent::dataInsert($data);
        if ($result) {
            CActivityContent::delCacheTopics($data['show_date']);
            $success = new MessageBag([
                'title' => '成功',
            ]);
        } else {
            $error = new MessageBag([
                'title' => '添加失败',
            ]);
            return back()->with(compact('error'))->withInput();
        }
        return redirect('/admin/brandActivity/scontent')->with(compact('success'));
    }

    public function editSave(Request $request, $id)
    {
        $params = $request->all();
        $name = $params['name'] ?? null;
        $value = $params['value'];
        if (!$name) {
            return response()->json([
                'message' => '操作失败',
                'status' => false,
            ]);
        }
        $data = [
            $name => $value,
            'update_time' => date('Y-m-d H:i:s', time()),
        ];
        ActivityContent::dataUpdate($data, ['id' => $id]);
        $success = [
            'message' => '操作成功',
            'status' => true,
        ];
        $show_date = ActivityContent::dataValue(['id' => $id],'show_date');
        CActivityContent::delCacheTopics($show_date);
        return response()->json($success);
    }

}